package com.stockz.downloaderx.yahoo;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.stockz.core.model.Bar;
import com.stockz.core.model.Scrip;

@Component
public class YahooQuoteParser{

	@Autowired
	@Qualifier("download.url.yahoo.param.format.value")
	private String format = "d1ohgl1pv";
	private SimpleDateFormat yahooDateFormat = new SimpleDateFormat("MM/dd/yyyy");
	
	public String getFormat() {
		return format;
	}
	
	public List<Bar> parse(String text, Scrip scrip) {
		if(StringUtils.hasText(text)){
			String[] tokens = text.split("\n");
			List<Bar> barList = new ArrayList<Bar>(tokens.length);
			for(String token : tokens){
				Bar bar = parseInternal(token, scrip);
				if(bar != null){
					barList.add(bar);
				}
			}
			return barList;
		}
		return null;
	}

	private Bar parseInternal(String text, Scrip scrip){
		if(StringUtils.hasText(text)){
			Bar bar = new Bar();
			String[] tokens = text.split(",");
			try {
				bar.setDate(yahooDateFormat.parse(tokens[0].replaceAll("\"", "")));
			} catch (ParseException e) {
				e.printStackTrace();
			}
			bar.setCode(scrip.getCode());
			bar.setOpen(Double.parseDouble(tokens[1]));
			bar.setHigh(Double.parseDouble(tokens[2]));
			bar.setLow(Double.parseDouble(tokens[3]));
			bar.setClose(Double.parseDouble(tokens[4]));
			bar.setPreviousClose(Double.parseDouble(tokens[5]));
			bar.setVolume(Double.parseDouble(tokens[6]));
			return bar;
		}
		return null;
	}
	
}
